# -*- coding: utf-8 -*-
#http://code.google.com/p/plsamples/source/browse/trunk/GrandMonde/getimageinfo.py
from models import Images, Setting
from google.appengine.api import memcache
from google.appengine.api import images
from google.appengine.ext import db
from google.appengine.ext import webapp
from django.http import HttpResponse   

import string
import StringIO
import struct
from google.appengine.api.images import Image
from userInfo import User

def getImageInfo(data):
    data = str(data)
    size = len(data)
    height = -1
    width = -1
    content_type = ''

    # handle GIFs
    if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
        # Check to see if content_type is correct
        content_type = 'image/gif'
        w, h = struct.unpack("<HH", data[6:10])
        width = int(w)
        height = int(h)

    # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/)
    # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR'
    # and finally the 4-byte width, height
    elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
          and (data[12:16] == 'IHDR')):
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[16:24])
        width = int(w)
        height = int(h)

    # Maybe this is for an older PNG version.
    elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
        # Check to see if we have the right content type
        content_type = 'image/png'
        w, h = struct.unpack(">LL", data[8:16])
        width = int(w)
        height = int(h)

    # handle JPEGs
    elif (size >= 2) and data.startswith('\377\330'):
        content_type = 'image/jpeg'
        jpeg = StringIO.StringIO(data)
        jpeg.read(2)
        b = jpeg.read(1)
        try:
            while (b and ord(b) != 0xDA):
                while (ord(b) != 0xFF): b = jpeg.read(1)
                while (ord(b) == 0xFF): b = jpeg.read(1)
                if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                    jpeg.read(3)
                    h, w = struct.unpack(">HH", jpeg.read(4))
                    break
                else:
                    jpeg.read(int(struct.unpack(">H", jpeg.read(2))[0])-2)
                b = jpeg.read(1)
            width = int(w)
            height = int(h)
        except struct.error:
            pass
        except ValueError:
            pass

    return content_type, width, height

def addImage(mime,description,bf):
    'Add Image'
    image=Images(mime=mime,description=description,bf=bf)
    image.size=len(image.bf)
    image.filetype,image.width,image.height=getImageInfo(bf)
    image.put()
    return image 

def addImage21(bf):
    image=Images(bf=bf)
    image.size=len(bf)
    image.filetype,image.width,image.height=getImageInfo(bf)
    if not image.filetype:return None
    image.mime=image.filetype
    image.put()
    return image

def addImage2(bf,name):
    image=Images(bf=bf)
    image.size=len(bf)
#    img=Image(bf)
#    
#    image.width=img.width
#    image.height=img.height
#    image.filetype='image/'+name.split('.')[1]
    image.filetype,image.width,image.height=getImageInfo(bf)
    if not image.filetype:return None
    image.mime=image.filetype
    image.name = name
    image.put()
    return image

def addImageCode(id,name):
    image = getImage(id)
    image.photoCode = id
    image.name=name
    db.put(image)

def getImage(id):
    try:
        id=int(id)
    except:
        return []
    return Images.get_by_id(id)

def resizeImage(id,size="images"):
    image=getImage(id)
    if not image:return None
    if size=="images":return image
    img=images.Image(image.bf)
    img.resize(width=240, height=240)
    img.im_feeling_lucky()
    image.bf=img.execute_transforms(output_encoding=images.JPEG)
    return image

def downImage(id,size="images"):
    key=id+size
    image=memcache.Client().get(key)
    if not image:
        image=resizeImage(id, size)
        memcache.Client().set(key,image,3600*24)
    return image

def delImage(key):
    image=Images.get(key)
    if image:image.delete()

def delImageByid(id):
    image=Images.get_by_id(int(id))
    if image:image.delete()

def getAllImages(index=0):
    return Images.all().order('-date').fetch(16,index*15)

def getPageing(index,page=0):
    s="/%s"
    if page==0:
        if index==16:return (None,"/1")
        else:return (None,None)
    if index==16:
        return ("/",s%(page+1)) if page==1 else (s %(page-1),s%(page+1))
    return ("/",None) if page==1 else (s %(page-1),None)


def checkUser(self):#验证是否具有这个用户
    setting=Setting().all().fetch(1)
    if setting:
        if False==setting[0].isPassword:
            return True
    username=self.request.get('UserName')
    password=self.request.get('UserPwd')
    if not username or not password:
        return False
#    greetings = db.GqlQuery("SELECT * FROM User where userName=:1 and passWord=:2",UserName,UserPwd)
    if 1== User().all().filter('userName =',username).filter('passWord =',password).count():
        return True
    else:
        return False

replacecode=[('$$',''),('**',''),('\r',''),('\n','[()]')]
def replaceChar(str):
    if str:
        for s,c in replacecode:
            str=str.replace(s,c)
    return str

